import React, { Component } from "react";
import { connect } from "react-redux";
import { Form, Switch, Checkbox, Input, Radio, InputNumber, Button, message } from "antd";
import Priority from "components/template/priority";
import { messages } from "share/common";
import Remind from "components/template/remind/remind";
import WrapFormItem from "components/wrap-form-item";
import beepTimerService from "../beep-timer.service";

@Form.create()
@connect(mapStateToProps)
class CorporateContent extends Component {
  state = {
    priority: {},
    saveLoading: false,
  };

  componentWillMount() {
    const { info, record } = this.props.params,
      { company } = this.props;
    let priority = info.id
      ? {
          levelOrgName: record.levelOrgName,
          levelOrgId: record.levelOrgId,
          levelCode: record.levelCode,
          distribution: record.isGlobal
            ? null
            : {
                companies: record.distribution
                  ? record.distribution.map((item) => ({
                      name: item.levelOrgName,
                      id: item.levelOrgId,
                    }))
                  : [],
              },
        }
      : {
          levelOrgName: company.setOfBooksName,
          levelOrgId: company.setOfBooksId,
          levelCode: "SET_OF_BOOK",
          distribution: {
            companies: [{ name: company.name, id: company.id }],
          },
        };
    this.setState({ priority });
  }

  handlePriority = (value) => {
    this.setState({ priority: value });
  };

  targetOptions = [
    {
      label: messages("basic-13.key113") /*本人*/,
      value: "CREATED_BY",
    },
    {
      label: messages("basic-13.key114") /*直属领导*/,
      value: "CREATED_BY_LEADER",
    },
    {
      label: messages("basic-13.key115") /*部门经理*/,
      value: "CREATED_BY_MANAGER",
    },
  ];

  options = [
    { label: messages("basic-13.key8") /*启用temp*/, value: true },
    { label: messages("basic-13.key227") /*不启用*/, value: false },
  ];

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err, value) => {
      if (!err) {
        const { priority } = this.state,
          { info } = this.props.params,
          { close } = this.props;
        if (!priority || (priority.distribution && priority.distribution.companies.length === 0)) {
          message.error(messages("basic-13.key225") /*请分配权限*/);
          return -1;
        }
        if (!value.warpTime.differenceDate) {
          message.error(messages("basic-13.key226") /*请输入触发时间*/);
          return -1;
        }
        this.setState({ saveLoading: true });
        this.warpRemind
          .saveValue()
          .then((id) => {
            let params = {
              enabledFlag: value.enabledFlag,
              code: "VendorInvoiceSubmitReminderTask",
              hour: Number(this.warpRemind.getValue().remindWarpValue.remindTimes[0].split(":")[0]),
              ...priority,
            };
            params.params = Object.assign(
              {
                title: value.title,
                content: value.content,
                prepaymentRemindPersonTypes: value.prepaymentRemindPersonTypes,
                regulationId: id,
                needBillContent: value.needBillContent,
                prepaymentRemindBaseDateType: "BEFORE_ESTIMATED_INVOICE_DATE",
                ...priority,
              },
              value.warpTime
            );
            let distributionList = params.distribution;
            delete params.distribution;
            delete params.params.distribution;
            params.isGlobal = !distributionList;
            params.params.isGlobal = !distributionList;
            distributionList &&
              (params.distribution = distributionList.companies.map((item) => ({
                levelCode: "COMPANY",
                levelOrgId: item.id,
                levelOrgName: item.name,
              })));
            distributionList &&
              (params.params.distribution = distributionList.companies.map((item) => ({
                levelCode: "COMPANY",
                levelOrgId: item.id,
                levelOrgName: item.name,
              })));
            params.params = JSON.stringify(params.params);
            info.id && (params.id = info.id);
            beepTimerService.newBeepTimer(params).then(() => {
              this.setState({ saveLoading: false });
              close(true);
            });
          })
          .catch((e) => {
            this.setState({ saveLoading: false });
            e.response && message.error(e.response.data.message);
          });
      }
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { close } = this.props;
    const { info, record } = this.props.params;
    const { priority, saveLoading } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10 },
      },
    };
    return (
      <div>
        <Form className={"new-form"}>
          <Form.Item label={messages("common.column.status") /*状态*/} {...formItemLayout}>
            {getFieldDecorator("enabledFlag", {
              rules: [{ required: true }],
              valuePropName: "checked",
              initialValue: info.hasOwnProperty("enabledFlag") ? info.enabledFlag : true,
            })(<Switch />)}
          </Form.Item>
          <Priority
            top="SET_OF_BOOK"
            disabled={info.hasOwnProperty("id")}
            disabledTop
            onChange={this.handlePriority}
            formItemLayout={formItemLayout}
            defaultValue={priority}
            single={false}
          />
          <h3 className="sub-title">{messages("basic-13.key12") /*提醒对象*/}</h3>
          <Form.Item label={messages("basic-13.key12") /*提醒对象*/} {...formItemLayout}>
            {getFieldDecorator("prepaymentRemindPersonTypes", {
              rules: [{ required: true }],
              initialValue: record.prepaymentRemindPersonTypes || ["CREATED_BY"],
            })(<Checkbox.Group options={this.targetOptions} />)}
          </Form.Item>
          <h3 className="sub-title">{messages("basic-13.key15") /*消息内容*/}</h3>
          <Form.Item label={messages("basic-13.key16") /*消息标题*/} {...formItemLayout}>
            {getFieldDecorator("title", {
              rules: [
                {
                  required: true,
                  message: messages("common.can.not.be.empty", {
                    arg1: messages("basic-13.key16") /*消息标题*/,
                  }) /*{arg1} 不能为空*/,
                },
                {
                  max: 50,
                  message: messages("common.max.characters.length", {
                    arg1: 50,
                  }) /*最多输入{arg1}个字符*/,
                },
              ],
              initialValue: record.title,
            })(<Input placeholder={messages("basic-13.key303") /*预付交票提醒*/} />)}
          </Form.Item>
          <Form.Item label={messages("basic-13.key17") /*消息正文*/} {...formItemLayout}>
            {getFieldDecorator("content", {
              rules: [
                {
                  required: true,
                  message: messages("common.can.not.be.empty", {
                    arg1: messages("basic-13.key17") /*消息正文*/,
                  }) /*{arg1} 不能为空*/,
                },
                {
                  max: 100,
                  message: messages("common.max.characters.length", {
                    arg1: 100,
                  }) /*最多输入{arg1}个字符*/,
                },
              ],
              initialValue: record.content,
            })(
              <Input.TextArea
                placeholder={
                  messages("basic-13.key304") /*存在预付未交票，请及时取得发票，发起到票支付申请并核销现有预付*/
                }
              />
            )}
          </Form.Item>
          <Form.Item label={messages("basic-13.key230") /*单据详情*/} {...formItemLayout}>
            {getFieldDecorator("needBillContent", {
              rules: [
                {
                  required: true,
                },
              ],
              initialValue: record.hasOwnProperty("needBillContent") ? record.needBillContent : true,
            })(<Radio.Group options={this.options} />)}
          </Form.Item>
          <h3 className="sub-title">{messages("basic-13.key18") /*消息触发*/}</h3>
          <Remind id={record.regulationId} onRef={(ref) => (this.warpRemind = ref)} hideType>
            <Form.Item label={messages("basic-13.key233") /*触发时间*/} {...formItemLayout}>
              {getFieldDecorator("warpTime", {
                rules: [
                  {
                    required: true,
                    message: messages("common.can.not.be.empty", {
                      arg1: messages("basic-13.key233") /*触发时间*/,
                    }) /*{arg1} 不能为空*/,
                  },
                ],
                initialValue: info.hasOwnProperty("id")
                  ? {
                      differenceDate: record.differenceDate,
                    }
                  : {},
              })(
                <WrapFormItem>
                  {(onChange, value) => (
                    <div>
                      {messages("basic-13.key305") /*预计到票日期前*/}
                      <InputNumber
                        precision={0}
                        min={0}
                        step={1}
                        value={value.differenceDate}
                        onChange={(day) => onChange({ differenceDate: day })}
                      />
                      {messages("basic-13.key236") /*天需要提醒员工*/}
                    </div>
                  )}
                </WrapFormItem>
              )}
            </Form.Item>
          </Remind>
        </Form>
        <div className="slide-footer">
          <Button type="primary" onClick={this.handleSave} loading={saveLoading}>
            {messages("common.ok") /*确定*/}
          </Button>
          <Button onClick={() => close()}>{messages("common.cancel") /*取消*/}</Button>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
  };
}

export default CorporateContent;
